<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="between">
            <div class="alitem">
              <el-icon @click="onClickBack">
                <ArrowLeftBold />
              </el-icon>
              <span>志愿表详情</span>
              <div class="userInfo" style="margin-left: 10px">
                <span>{{ studentData.studentName }}</span>
                <span>{{ studentInfo.sex == '1' ? '女' : '男' }}</span>
                <span> {{ studentData.gkaProvinceName }}</span>
                <span>{{ zyInfo.score }}分</span>
                <span>{{
                  zyInfo.section > 0 ? zyInfo.section + '位' : ''
                }}</span>
                <span>{{ zyInfo.sgname }}</span>
                <span>{{ zyInfo.batch }}</span>
              </div>
            </div>
            <div class="alitem">
              <el-tooltip effect="dark" content="个人资料" placement="top">
                <el-icon @click="userInfoChange('first')">
                  <Postcard />
                </el-icon>
              </el-tooltip>
              <!-- <el-tooltip effect="dark" content="成绩分析" placement="top">
                <el-icon class="maginleft20" @click="userInfoChange('fourth')">
                  <DataAnalysis />
                </el-icon>
              </el-tooltip> -->
              <!-- <el-tooltip effect="dark" content="用户关注" placement="top">
                <el-icon class="maginleft20" @click="userInfoChange('fourth1')">
                  <User />
                </el-icon>
              </el-tooltip> -->
              <!-- <el-tooltip effect="dark" content="填报统计" placement="top">
                <el-icon class="maginleft20" @click="userInfoChange('fourth2')">
                  <HelpFilled />
                </el-icon>
              </el-tooltip> -->
              <el-tooltip effect="dark" content="志愿表" placement="top">
                <el-icon class="maginleft20" @click="userInfoChange('fourth3')">
                  <Tickets />
                </el-icon>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="下载打印版"
                placement="top"
                v-if="zyInfo.status != 0"
              >
                <el-icon class="maginleft20" @click="downloadPrint">
                  <Printer />
                </el-icon>
              </el-tooltip>
              <!-- <el-divider direction="vertical" />
              <el-tooltip effect="dark" content="一键填报" placement="top">
                <el-icon class="maginleft10">
                  <Printer />
                </el-icon>
              </el-tooltip> -->
            </div>
          </div>
        </div>
      </template>
      <el-row :gutter="20" justify="space-between">
        <el-col :span="7">
          <div class="alitem">
            <!-- <el-icon :size="20" v-if="zyInfo.status !== 0">
              <Edit @click="dialogFormVisible = true" />
            </el-icon> -->
            <div style="margin: 0 10px; font-weight: bold">
              {{ zyInfo.title }}
            </div>
            <div style="font-size: 14px">
              数据更新时间: {{ zyInfo.lastModificationTime }}
            </div>
          </div>
        </el-col>
        <el-col :span="16" v-if="zyInfo.status != 0">
          <div class="alitem right" style="font-size: 15px">
            <div class="alitem">
              一键展开&nbsp;
              <el-switch v-model="allUnfold" />
            </div>
            <div class="alitem" style="margin: 0 20px">
              录取概率&nbsp;
              <el-switch v-model="showChancelv" />
            </div>
            <div
              class="alitem"
              v-if="!(studentInfo.pid == 51 && teacherInfo.newsc == 1)"
            >
              同步至学生&nbsp;
              <el-switch v-model="zyInfo.isStudentSee" @change="zyInfoChange" />
            </div>
            <el-dropdown @command="sortHandleCommand">
              <div class="el-dropdown-link alitem" style="margin: 0 20px">
                <div class="curr" style="color: #333">快速排序</div>
                <el-icon color="#333">
                  <arrow-down />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="chance">录取概率</el-dropdown-item>
                  <el-dropdown-item command="rank">院校排名</el-dropdown-item>
                  <el-dropdown-item command="position"
                    >位次排序</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div class="curr" style="margin-right: 20px" @click="onClickUpdate">
              修改
            </div>
            <div
              class="curr"
              @click="onClickSave"
              :style="
                isInitialLoad ? 'color:red;border-bottom:2px solid red;' : ''
              "
            >
              保存
            </div>
            <el-dropdown @command="moreHandleCommand">
              <div
                class="curr"
                style="margin-left: 20px; color: #333; font-size: 15px"
                @mouseover="moreMouseover"
              >
                更多
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="save">
                    <el-button class="more-button" text>另存为</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item command="download">
                    <el-button class="more-button" v-if="isDpwnLoadShow" text
                      >下载</el-button
                    >
                    <el-button class="more-button" v-else loading text
                      >下载</el-button
                    >
                  </el-dropdown-item>
                  <!-- <el-dropdown-item command="share" @mouseover="isShowQrImage = true" @mouseout="isShowQrImage = false"> -->
                  <el-dropdown-item command="share">
                    <el-button
                      class="more-button"
                      v-if="isSharShow"
                      text
                      @mouseout="isShowQrImage = false"
                      >分享</el-button
                    >
                    <el-button class="more-button" v-else loading text
                      >分享</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div
              v-show="isShowQrImage"
              class="qr-box"
              @mouseout="isShowQrImage = false"
            >
              <img style="width: 100%; height: 100%" :src="shareQrImage" />
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="classifyheader margintop">
        <div class="flex sizebg">
          <div style="margin-left: 45px" class="alitem">排序</div>
          <div style="margin-left: 44px" class="alitem">录取概率</div>
          <div style="margin-left: 44px" class="alitem">院校</div>
        </div>
        <div class="flex sizeinfo">
          <div class="alitem" style="margin-right: 20px">
            {{ zyInfo.today_year }}招生计划
          </div>
          <div style="width: 53px" class="center">历年</div>
          <div style="width: 90px" class="center">
            {{ zyInfo.today_year - 1 }}
          </div>
          <div style="width: 90px" class="center">
            {{ zyInfo.today_year - 2 }}
          </div>
          <div style="width: 90px" class="center">
            {{ zyInfo.today_year - 3 }}
          </div>
          <div style="margin-left: 60px; margin-right: 20px">操作</div>
        </div>
      </div>
      <sdVolunteerlist
        v-if="zy_type == 1"
        :status="status"
        :studentData="studentData"
        :allUnfold="allUnfold"
        :showChancelv="showChancelv"
        :batchs="batchs"
        :currentSort="currentSort"
        @changeSdInitialLoad="changeSdInitialLoad"
      />
      <jsVolunteerlist
        v-else-if="zy_type == 2"
        :status="status"
        :studentData="studentData"
        :allUnfold="allUnfold"
        :showChancelv="showChancelv"
        :batchs="batchs"
        :currentSort="currentSort"
        @changeInitialLoad="changeInitialLoad"
      />
      <scVolunteerlist
        v-else
        :status="status"
        :studentData="studentData"
        :allUnfold="allUnfold"
        :showChancelv="showChancelv"
        :batchs="batchs"
        :currentSort="currentSort"
        @changeScInitialLoad="changeScInitialLoad"
      />
    </el-card>

    <userInfoDialog ref="userInfo" :studentData="studentData"></userInfoDialog>

    <el-dialog v-model="dialogFormVisible" title="志愿表命名" width="500">
      <el-form>
        <el-form-item label="志愿表名称" :label-width="formLabelWidth">
          <el-input
            v-model="volunteerTitle"
            autocomplete="off"
            placeholder="请输入志愿表名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onClickUpdateTitle">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import userInfoDialog from '@/views/leader/volunteer/module/userInfoDialog.vue';
import jsVolunteerlist from './module/jsVolunteerlist.vue';
import scVolunteerlist from './module/scVolunteerlist.vue';
import sdVolunteerlist from './module/sdVolunteerlist.vue';
import { useRoute, useRouter } from 'vue-router';
import bus from '@/utils/bus.js';
import {
  getZyInfo,
  zySave,
  shareZY,
  shareZYNew,
  gkbInfo,
} from '/src/api/appv2/appv2.js';
import volunteersStore from '@/store/modules/volunteerInfos';
import { ElMessage, ElMessageBox } from 'element-plus';
import QRCode from 'qrcode';

const teacherInfo = JSON.parse(localStorage.getItem('userDateInfo'));

// 路由信息
const router = useRouter();
// 路由信息
const route = useRoute();
// 志愿表仓库
const volunteerStore = volunteersStore();

const userInfo = ref(null);

const batchs = ref([]);
const zyInfo = ref({}); // 志愿详情信息

// const storeVolunteerInfos = computed(() => volunteerStore.volunteerInfos)
const volunteerInfos = ref([]); // 志愿表信息
const tempVolunteerInfos = ref([]);
const index = ref(''); // 志愿表的index
const zy_type = ref(''); // 志愿表的index
const studentData = ref({}); // 学生数据
const studentInfo = ref({}); // 学生信息
const allUnfold = ref(false); // 是否一键展开
const showChancelv = ref(true); // 是否显示录取率
const dialogFormVisible = ref(false); // 是否显示修改志愿表名称弹窗
const volunteerTitle = ref(''); // 志愿表标题

const isShowQrImage = ref(false); // 是否显示分享二维码
const shareUrl = ref(null); // 分享地址
const shareQrImage = ref(null); // 分享二维码图片
const currentSort = ref(0); // 当前排序 chance-录取率 rank-院校排名 position-位次
const isInitialLoad = ref(false);
const isDpwnLoadShow = ref(true);
const isSharShow = ref(true);
// 当前志愿表状态 0不可编辑
const status = ref(0);
const changeInitialLoad = (isInitial) => {
  isInitialLoad.value = isInitial;
};
const changeSdInitialLoad = (sdIsInitial) => {
  isInitialLoad.value = sdIsInitial;
};
const changeScInitialLoad = (scIsInitial) => {
  isInitialLoad.value = scIsInitial;
};
bus.emit('handlePathTextChange', '编辑志愿表');

onBeforeRouteLeave((to, from, next) => {
  bus.emit('handlePathTextChange', '');
  next();
});

init();

function init() {
  let data = JSON.parse(route.query.data);
  index.value = data.index;
  status.value = data.status || data.studentData.isGKB;
  zy_type.value = data.zy_type;
  studentData.value = data.studentData;
  studentInfo.value = data.studentData.student;

  volunteerStore.setVolunteerInfos(null);
  getVolunteerInfo();

  gkbInfo({
    pid: studentInfo.value.pid,
    studentId: studentData.value.studentId,
  }).then(() => {});
}

function onClickBack() {
  router.replace({
    path: '/leader/Filling',
  });
}

function userInfoChange(val) {
  userInfo.value.openChange(val);
}

// 获取志愿表信息
function getVolunteerInfo() {
  getZyInfo({
    index: index.value,
    studentId: studentData.value.studentId,
  }).then((res) => {
    localStorage.setItem('equivalents', JSON.stringify(res.data.equivalents));

    batchs.value = res.data.batchs;
    zyInfo.value = res.data;
    zyInfo.value.isStudentSee = !!zyInfo.value.isStudentSee;
    volunteerInfos.value = zyInfo.value.volunteerInfos;
    tempVolunteerInfos.value = zyInfo.value.volunteerInfos;
    volunteerTitle.value = zyInfo.value.title;
    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  });
}

// 快速排序
function sortHandleCommand(type) {
  if (zy_type.value == 3) {
    volunteerInfos.value = volunteerStore.volunteerInfos;
  }

  switch (type) {
    case 'chance':
      chanceSort();
      break;
    case 'rank':
      rankSort();
      break;
    case 'position':
      positionSort();
  }

  currentSort.value += 1;
}

// 录取率排序
function chanceSort() {
  if (zy_type.value == 3) {
    let keys = Object.keys(volunteerInfos.value);
    let volunteers = Object.values(volunteerInfos.value);

    volunteers = volunteers
      .slice()
      .sort((a, b) => a.collegeData.chance - b.collegeData.chance);

    for (let i in volunteers) {
      volunteerInfos.value[keys[i]] = volunteers[i];
    }

    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  } else {
    volunteerInfos.value = volunteerInfos.value
      .slice()
      .sort((a, b) => a.chance - b.chance);
    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  }
}

// 院校排名排序
function rankSort() {
  if (zy_type.value == 3) {
    let keys = Object.keys(volunteerInfos.value);
    let volunteers = Object.values(volunteerInfos.value);

    volunteers = volunteers
      .slice()
      .sort((a, b) => a.collegeData.rank - b.collegeData.rank);

    for (let i in volunteers) {
      volunteerInfos.value[keys[i]] = volunteers[i];
    }

    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  } else {
    volunteerInfos.value = volunteerInfos.value
      .slice()
      .sort((a, b) => a.rank - b.rank);
    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  }
}

// 位次排序
function positionSort() {
  if (zy_type.value == 3) {
    let keys = Object.keys(volunteerInfos.value);
    let volunteers = Object.values(volunteerInfos.value);

    volunteers = volunteers
      .slice()
      .sort((a, b) => a.collegeData.minRank - b.collegeData.minRank);

    for (let i in volunteers) {
      volunteerInfos.value[keys[i]] = volunteers[i];
    }

    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  } else {
    volunteerInfos.value = volunteerInfos.value
      .slice()
      .sort((a, b) => a.minRank - b.minRank);
    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  }
}

// 更多选项
function moreHandleCommand(type) {
  let data = {
    index: index.value,
    studentId: studentData.value.studentId,
    fronttype: 3,
  };
  switch (type) {
    case 'save': // 另存为
      copyVolunteer();
      break;
    case 'download': // 下载
      if (isInitialLoad.value) {
        ElMessageBox.confirm(
          '当前志愿表信息有修改，未保存将会下载原有志愿表是否下载？',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            isDpwnLoadShow.value = false;
            shareUrl.value = null;

            shareZY(data)
              .then((res) => {
                ElMessageBox.confirm('志愿报告已生成，是否立即下载？', '提示', {
                  confirmButtonText: '立即下载',
                  cancelButtonText: '稍后下载',
                  type: 'warning',
                })
                  .then(() => {
                    shareUrl.value = res.data.url;
                    window.location.href = shareUrl.value;
                    ElMessage.success('下载成功');
                    isDpwnLoadShow.value = true;
                    // 生成二维码
                    generateQR(shareUrl.value).then((res) => {
                      shareQrImage.value = res;
                    });
                  })
                  .catch(() => {
                    isDpwnLoadShow.value = true;
                    ElMessage({
                      type: 'info',
                      message: '已取消',
                    });
                  });
              })
              .catch(() => {
                ElMessage({
                  type: 'error',
                  message: '获取链接失败，请重试！',
                });
                isDpwnLoadShow.value = true;
              });
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消',
            });
          });
      } else {
        isDpwnLoadShow.value = false;
        shareUrl.value = null;

        shareZY(data)
          .then((res) => {
            ElMessageBox.confirm('志愿报告已生成，是否立即下载？', '提示', {
              confirmButtonText: '立即下载',
              cancelButtonText: '稍后下载',
              type: 'warning',
            })
              .then(() => {
                shareUrl.value = res.data.url;
                window.location.href = shareUrl.value;
                isDpwnLoadShow.value = true;
                ElMessage.success('下载成功');
                // 生成二维码
                generateQR(shareUrl.value).then((res) => {
                  shareQrImage.value = res;
                });
              })
              .catch(() => {
                isDpwnLoadShow.value = true;
                ElMessage({
                  type: 'info',
                  message: '已取消',
                });
              });
          })
          .catch(() => {
            ElMessage({
              type: 'error',
              message: '获取链接失败，请重试！',
            });
            isDpwnLoadShow.value = true;
          });
      }

      // }
      break;
    case 'print': // 打印
      break;
    case 'share': // 分享
      isSharShow.value = false;

      shareZY(data)
        .then((res) => {
          shareUrl.value = res.data.url;
          // 生成二维码
          generateQR(shareUrl.value).then((res) => {
            shareQrImage.value = res;
            isShowQrImage.value = true;
            isSharShow.value = true;
          });
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '获取链接失败，请重试！',
          });
          isSharShow.value = true;
        });
      // }
      break;
  }
}

// 复制志愿表到专家
function copyVolunteer() {
  // let volunteer = volunteerList.value[index]
  zySave({
    index: zyInfo.value.index,
    operate: 'copy',
    studentId: studentData.value.studentId,
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '另存为成功',
    });
  });
}

const generateQR = async (text) => {
  try {
    const opts = {
      errorCorrectionLevel: 'H',
      type: 'image/png',
      quality: 0.9,
      margin: 1,
    };
    const qrImage = await QRCode.toDataURL(text, opts);
    return qrImage;
  } catch (err) {
    console.error(err);
  }
};

// 点击保存志愿表
function onClickSave() {
  let data = {};
  data['volunteerInfos'] = JSON.stringify(volunteerStore.volunteerInfos);

  updateZyInfo(data);
}

// 点击修改志愿表
function onClickUpdate() {
  if (isInitialLoad.value) {
    ElMessageBox.confirm(
      '当前志愿表信息有修改尚未保存，是否放弃更改并离开当前页面？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      volunteerStore.setVolunteerInfos(tempVolunteerInfos.value);
      gotoUpdateVolunteer();
    });
  } else {
    gotoUpdateVolunteer();
  }
}

function gotoUpdateVolunteer() {
  // volunteerStore.setVolunteerInfos(volunteerInfos.value);

  let body = {
    update: true,
    batchInfo: {
      batch: zyInfo.value.batch,
      score: zyInfo.value.score,
      section: zyInfo.value.section,
      sgname: zyInfo.value.sgname,
    },
    studentData: studentData.value,
  };
  let jsonStr = JSON.stringify(body);
  router.push({
    path: '/leader/volunteer',
    query: {
      data: jsonStr,
    },
  });
}

// 修改志愿表标题
function onClickUpdateTitle() {
  dialogFormVisible.value = false;
  zyInfo.value.title = volunteerTitle.value;

  let data = {};
  data['title'] = volunteerTitle.value;

  updateZyInfo(data);
}

// 修改志愿表是否同步至学生
function zyInfoChange() {
  let data = {};
  data['isStudentSee'] = zyInfo.value.isStudentSee ? 1 : 0;
  updateZyInfo(data);
}

// 更新志愿表信息
function updateZyInfo(data) {
  data['index'] = index.value;
  data['studentId'] = studentData.value.studentId;
  zySave(data).then(() => {
    tempVolunteerInfos.value = JSON.parse(data['volunteerInfos']);
    isInitialLoad.value = false;
    // 修改成功
    ElMessage({
      message: '更新成功',
      type: 'success',
    });
  });
}

// 下载打印版
function downloadPrint() {
  // 修改为保存，提示
  if (isInitialLoad.value) {
    ElMessageBox.confirm(
      '当前志愿表信息有修改，未保存将会下载原有志愿表是否下载？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        // 成功拿到下载链接，再次提示
        ElMessageBox.confirm('志愿报告已生成，是否立即下载？', '提示', {
          confirmButtonText: '立即下载',
          cancelButtonText: '稍后下载',
          type: 'warning',
        })
          .then(() => {
            handleShareZYNew();
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消',
            });
          });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        });
      });
  } else {
    // 成功拿到下载链接，再次提示
    ElMessageBox.confirm('志愿报告已生成，是否立即下载？', '提示', {
      confirmButtonText: '立即下载',
      cancelButtonText: '稍后下载',
      type: 'warning',
    })
      .then(() => {
        handleShareZYNew();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        });
      });
  }
}

const handleShareZYNew = () => {
  let data = {
    index: index.value,
    studentId: studentData.value.studentId,
    fronttype: 3,
  };
  shareZYNew(data)
    .then((res) => {
      ElMessage({
        message: '下载成功',
        type: 'success',
      });
      window.location.href = res.data.url;
      // window.open(res.data.url);
    })
    .catch(() => {
      ElMessage({
        message: '下载失败，请重试',
        type: 'error',
      });
    });
};
</script>
<style lang="scss" scoped>
.more-button {
  width: 100px;
}

.box-card {
  margin: 20px;
  width: auto;
  height: calc(100vh - 120px);
  overflow-y: auto;

  .tabs {
    color: #000000;
    font-weight: 600;
    cursor: pointer;
  }

  .active {
    color: #004cf7;
    font-weight: 600;
    cursor: pointer;
  }

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .userInfo {
      margin-left: 30px;
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
      line-height: 16px;

      span {
        margin-left: 8px;
      }
    }

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.classifyheader {
  background: #fafafa;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #86909c;
  letter-spacing: 0;
  line-height: 28px;
  padding-right: 80px;
}

.qr-box {
  position: absolute;
  top: 180px;
  right: 0;
  width: 120px;
  height: 120px;
  border: 1px #efefef solid;
  padding: 5px;
  background-color: white;
  z-index: 999;
  box-shadow: 1px 1px 4px 1px #efefef;
  border-radius: 5px;
}
</style>
